<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检索" prop="search">
        <el-input v-model="queryParams.search" placeholder="请输入检索信息" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="供应商" prop="providerId">
        <el-select v-model="queryParams.providerId" placeholder="请选择供应商">
          <el-option v-for="item in providerList" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择日期" prop="dateTime">
        <el-date-picker clearable v-model="queryParams.dateTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="业务类型" prop="businessId">
        <el-select v-model="queryParams.businessId" placeholder="请选择业务类型">
          <el-option label="生产入库" value="0"></el-option>
          <el-option label="采购入库" value="1"></el-option>
          <el-option label="退货入库" value="2"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="合同类型" prop="contractId">
        <el-select v-model="queryParams.contractId" placeholder="请选择合同类型">
          <el-option label="采购合同" value="0"></el-option>
          <el-option label="销售合同" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="申请状态" prop="createStatus">
        <el-select v-model="queryParams.createStatus" placeholder="请选择申请状态">
          <el-option label="待审核" value="0"></el-option>
          <el-option label="已审核" value="1"></el-option>
          <el-option label="未提交" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="updateStatus">
        <el-select v-model="queryParams.updateStatus" placeholder="请选择审核状态">
          <el-option label="驳回" value="0"></el-option>
          <el-option label="审核通过" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="单据状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择单据状态">
          <el-option label="未分拣" value="0"></el-option>
          <el-option label="审核已分拣" value="1"></el-option>
          <el-option label="已发货" value="3"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['carbon:Grain:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['carbon:Grain:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['carbon:Grain:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="GrainList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50" label="编号" />
      <el-table-column label="单据号" align="center" prop="orderId" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.status == '0'">
            未采购
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.status == '1'">
            采购中
          </el-tag>
          <el-tag effect="dark" type="success" v-else>
            采购完成
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="createBy" />
      <el-table-column label="申请日期" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createStatus, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="createStatus">
        <template slot-scope="scope">
          <el-tag effect="dark"
            :type="scope.row.createStatus == '0' ? 'danger' : (scope.row.createStatus == '1' ? 'warning' : 'primary')">
            {{ scope.row.createStatus == '0' ? '待审核' : (scope.row.createStatus == '1' ? '已审核' : '未提交') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="updateBy" />
      <el-table-column label="审核日期" align="center" prop="updateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="enterStatus">
        <template slot-scope="scope">

          <el-tag effect="dark" type="danger" v-if="scope.row.enterStatus == '2'">
            驳回
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.enterStatus == '1'">
            审核通过
          </el-tag>
          <el-tag effect="dark" v-else>
            待审核
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['carbon:Grain:edit']">修改</el-button>
          <el-button v-if="scope.row.enterStatus == '0'" size="mini" type="text" icon="el-icon-message-solid"
            @click="handleRepairStatus(scope.row)" v-hasPermi="['carbon:Grain:edit']">审核</el-button>
          <el-button
            v-if="scope.row.updateStatus == '1' && scope.row.storageStatus == '0' && scope.row.enterStatus == '1'"
            size="mini" type="text" icon="el-icon-download" @click="handleUpdateStatus(scope.row)">入库</el-button>
          <el-button v-if="scope.row.createStatus == '2'" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改入库信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据">
          <el-select v-if="form.id == null" v-model="form.orderId" placeholder="请输入单据id"
            :disabled="this.type != '0' || this.type == '6'">
            <el-option v-for="item in orderIdList" :key="item.id" :label="item.orderId" :value="item.orderId"></el-option>
          </el-select>
          <el-input v-if="form.id != null" v-model="form.orderId" placeholder="请输入单据id" :disabled="true" />
        </el-form-item>
        <el-form-item label="业务类型" prop="businessId">
          <el-select v-model="form.businessId" placeholder="请选择业务类型" :disabled="this.type == '123' || this.type == '6'">
            <el-option label="生产入库" :value="'0'"></el-option>
            <el-option label="采购入库" :value="'1'"></el-option>
            <el-option label="退货入库" :value="'2'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同类型" prop="contractId" v-if="form.id == null">
          <el-select v-model="form.contractId" placeholder="请选择合同类型" :disabled="this.type != '0' || this.type == '6'">
            <el-option label="采购合同" :value="'0'"></el-option>
            <el-option label="销售合同" :value="'1'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="providerId">
          <el-select v-model="form.providerId" placeholder="请选择供应商" :disabled="this.type == '123' || this.type == '6'">
            <el-option v-for="item in providerList" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="wareName">
          <el-cascader v-model="form.wareName" :options="wareList" :props="props" clearable
            :disabled="this.type == '123' || this.type == '6'"></el-cascader>
        </el-form-item>
        <el-form-item label="生产单位" prop="productName">
          <el-cascader v-model="form.productName" :options="productList" :props="props1" clearable
            :disabled="this.type == '123' || this.type == '6'"></el-cascader>
        </el-form-item>


        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"
            :disabled="this.type == '123' || this.type == '6'" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="this.type != '6'">
        <el-button type="success" @click="submitForm1" v-if="this.type != '123'">保 存</el-button>
        <el-button type="primary" @click="submitForm" v-if="this.type != '123'">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-if="this.type == '6'">
        <el-button type="success" @click="submitForm2">通 过</el-button>
        <el-button type="primary" @click="submitForm3">驳 回</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderIdList, changeCreateStatus, updateEnterStatus, changeGrainStatus, listGrain, getGrain, delGrain, addGrain, updateGrain } from "@/api/wms/grain";
import { providerList } from "@/api/wms/provider"
import { getCascaderWare } from "@/api/wms/ware"
import { getProductTreeNode } from "@/api/wms/product"
export default {
  name: "Grain",
  data () {
    return {
      orderIdList: [],
      // 情况 123
      type: '0',
      // 生产厂家
      productList: [],
      props1: {
        value: 'id',
        label: 'name',
        children: "children"
      },
      //仓库
      wareList: [],
      props: {
        value: 'id',
        label: 'wareName',
        children: "children"
      },
      // 供应商
      providerList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库信息表格数据
      GrainList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        flag: 1
      },
      // 表单参数
      form: {
        // 单据状态
        orderStatus: '0',
        // 入库状态
        status: '0',
        // 申请状态
        createStatus: '0',
        // 审核状态
        updateStatus: '0'
      },
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "单据不能为空", trigger: "blur" }
        ],
        businessId: [
          { required: true, message: "业务类型", trigger: "change" }
        ],
        contractId: [
          { required: true, message: "合同类型", trigger: "change" }
        ],
        providerId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
        productName: [
          { required: true, message: "生产单位", trigger: "change" }
        ],
        wareName: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],

      }
    };
  },
  created () {
    this.getList();
    this.getproviderList();
    this.getProductTreeList()
    this.getWareList()
  },
  methods: {
    // 获取所有单据Id
    getOrder () {
      getOrderIdList().then(res => {
        this.orderIdList = res.data
      })
    },
    // 获取生产单位树形结构
    getProductTreeList () {
      getProductTreeNode().then(res => {
        this.productList = res.data
      })
    },
    // 格式化数据，递归将空的children置为undefined
    formatData (data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.formatData(data[i].children)
        }
      }
      return data;
    },
    // 获取仓库信息
    getWareList () {
      getCascaderWare().then(res => {
        this.wareList = this.formatData(res.data)
      })
    },
    /** 补货申请审核 */
    handleRepairStatus (row) {
      this.reset();
      const id = row.id || this.ids
      this.type = '6'
      getGrain(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "审核入库信息";
      });
    }, /** 通过按钮 */
    submitForm2 () {
      this.form.enterStatus = '1';
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateEnterStatus(this.form.id, this.form.repairStatus).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.reset();
            this.getList();
          });
        }
      });
    },
    /** 驳回按钮 */
    submitForm3 () {
      this.form.enterStatus = '2';
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateEnterStatus(this.form.id, this.form.enterStatus).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.reset();
            this.getList();
          });
        }
      });
    },
    // 入库
    handleUpdateStatus (row) {
      changeGrainStatus(row.id).then(res => {
        this.$message.success("入库成功")
        this.getList()
      })
    },
    // 所有供应商信息
    getproviderList () {
      providerList().then(res => {
        this.providerList = res.data
      })
    },
    /** 查询入库信息列表 */
    getList () {
      this.loading = true;
      listGrain(this.queryParams).then(response => {
        this.GrainList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.type = "0"
      this.form = {
        createStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        flag: 1
      }
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.getOrder()
      this.getProductTreeList()
      this.getWareList()
      this.reset();
      this.open = true;
      this.title = "添加入库信息";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.getOrder()
      this.reset();
      const id = row.id || this.ids
      if (row.createStatus != '2') {
        this.type = '123'
      } else {
        this.type = '4'
      }

      getGrain(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改入库信息";
      });
    },
    /** 保存按钮 */
    submitForm1 () {
      this.form.createStatus = '3';
      this.submitForm();
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.createStatus == '3') {
            this.form.createStatus = '2'
          } else {
            this.form.createStatus = '0'
          }
          addGrain(this.form).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.reset();
            console.log(this.form);
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除入库信息编号为"' + ids + '"的数据项？').then(function () {
        return delGrain(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
  }
};
</script>
